package usw.webserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import usw.webserver.helper.ConfigHelper;

public class ApacheServer extends Thread {

	private static final int N_THREADS = 10;
	
	private static final int DEFAULT_PORT = 8080;
	
    public ApacheServer()
    {
    	port = DEFAULT_PORT;
    	webRootPath = ".";
    }
    
    public ApacheServer(int s_port, String s_webRootPath)
    {
    	port = s_port;
    	webRootPath = s_webRootPath;
    }
    
    /**
     * 
     * @param port
     * @throws IOException
     */
	public void startServer() throws Exception 
	{	    	
		ServerSocket s = new ServerSocket(port);
		System.out.println("Web server listening on port " + port + " (press CTRL-C to quit)");
		ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
		
		while (true) 
		{
			executor.submit(new RequestHandler(s.accept(), webRootPath));
		}
	}
	
	private	static int		port;
	private	static String	webRootPath;
	
    /**
     * 
     * @param args
     */
    public static void main(String[] args)
    {  			
    	System.out.println("================================================");
		System.out.println("Simulated ApacheServer Started");
		
		port = ConfigHelper.getServerPort();
		webRootPath = ConfigHelper.getWebRootPath();
		
		System.out.println("Listen to Port: " + port);
		System.out.println("WebRootPath: "    + webRootPath);
		System.out.println("================================================");
		
		ApacheServer	webServer = new ApacheServer(port, webRootPath);
		
		try {
			webServer.startServer();
		} catch (IOException e) {
			
			e.printStackTrace();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
    }  
      
}
